package mydessertstore.web.servlet;

import mydessertstore.domain.Account;
import mydessertstore.domain.Category;
import mydessertstore.domain.Item;
import mydessertstore.domain.Product;
import mydessertstore.service.CatalogService;
import mydessertstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ViewProductServlet extends HttpServlet {
    private  static final String VIEW_PRODUCT = "/WEB-INF/jsp/catalog/product.jsp";
    private String productId;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset = UTF-8");

        productId = req.getParameter("productId");
        CatalogService catalogService = new CatalogService();
        Product product = catalogService.getProduct(productId);
        List<Item> itemList = catalogService.getItemListByProduct(productId);

        //根据product得到搜索结果的类，放在return to的a标签里
        String categoryId = product.getCategoryId();
        Category category = catalogService.getCategory(categoryId);

        HttpSession session = req.getSession();
        session.setAttribute("product",product);
        session.setAttribute("itemList",itemList);
        session.setAttribute("category" ,category );
        // System.out.println(itemList.size());

        //日志功能
        Account account;
        account = (Account) session.getAttribute("account");
        if(account!=null) {

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 查看productId为"+productId+"的product界面" ;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        else{
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 查看productId为"+productId+"的product界面" ;
            logService.insertLogInfo("未登录用户", logInfo);
        }

        req.getRequestDispatcher(VIEW_PRODUCT).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset = UTF-8");

        doGet(req, resp);
    }
}
